<?php

class PHPFileStorage {
	
	private $filePath;
	
	public function __construct($filePath) {
		$this->filePath = $filePath;

		if (file_exists($this->filePath) == false) {
			file_put_contents($this->filePath, "<?php");
		}
	}
	
	/**
	 * Write item/user to the file.
	 */
	public function writeItem($key, $content) {
		// Hide data as a comment.
		$newLine = "\n//\040$key\040$content";
		
		//lock file for writing (append)
		$fileHandle = fopen($this->filePath, "a");
		fwrite($fileHandle, $newLine, strlen($newLine)); 
		fclose($fileHandle);
	}
	
	/**
	 * Empty file and prepare start of file with <?php
	 * @var file $fileHandle
	 */
	public function emptyFile() {
		$fileHandle = fopen($this->filePath, "w+");
		fwrite($fileHandle, "<?php"); 
		fclose($fileHandle);
	}
	
	public function changeItem($key, $content) {
		$users = $this->readAll();
		// Find the user in list.
		foreach ($users as $user => $value) {
			if ($user == $key) {
				$users[$user] = $content;
				break;
			}
		}
		
		$this->emptyFile();
		// Write all the users to file again.
		foreach ($users as $user1 => $content1) {
			$this->writeItem($user1, $content1);
		}
	}
	
	/**
	 * Read a specific item/user.
	 */
	public function readItem($key) {
		$fileContents = file_get_contents($this->filePath);
		$fileLines = explode("\n", $fileContents);
		$numLines = count($fileLines);
		for ($i = 1; $i < $numLines; $i++) {
			$line = $fileLines[$i];
			$lineParts = explode("\040", $line);

			if (strcmp($key, $lineParts[1]) == 0) {
				$contentFound = $lineParts[2];
				break;
			}
		}
		if (isset($contentFound)) {
			return $contentFound;
		}
		return "";
	}
	
	public function readAll() {
		$ret = array();

		$fileContents = file_get_contents($this->filePath);
		$fileLines = explode("\n", $fileContents);
		$numLines = count($fileLines);
		for ($i = 1; $i < $numLines; $i++) {
			$line = $fileLines[$i];
			$lineParts = explode("\040", $line);

			$ret[$lineParts[1]] = $lineParts[2];
		}
		
		return $ret;
	}
}
